package com.himiotech.core.project.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.himiotech.core.framework.helper.constant.GenConstants;
import com.himiotech.core.framework.helper.exception.HimioException;
import com.himiotech.core.framework.helper.utils.file.FileUtils;
import com.himiotech.core.project.data.mapper.GenTableColumnMapper;
import com.himiotech.core.project.data.mapper.GenTableMapper;
import com.himiotech.core.project.helper.utils.GenUtils;
import com.himiotech.core.project.helper.utils.TplUtils;
import com.himiotech.core.project.model.entity.gen.GenTable;
import com.himiotech.core.project.model.entity.gen.GenTableColumn;
import com.himiotech.core.project.model.metadata.GenTableMetadata;
import com.himiotech.core.project.service.IGenTableService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 业务 服务层实现
 *
 * @author ruoyi
 * @author wuwenbin
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class GenTableServiceImpl extends ServiceImpl<GenTableMapper, GenTable> implements IGenTableService {

    @Autowired
    private GenTableMapper genTableMapper;

    @Autowired
    private GenTableColumnMapper genTableColumnMapper;

    /**
     * 查询业务信息
     *
     * @param id 业务ID
     * @return 业务信息
     */
    @Override
    public GenTable selectGenTableById(Long id) {
        GenTable genTable = genTableMapper.selectGenTableById(id);
        setTableFromOptions(genTable);
        return genTable;
    }

    /**
     * 查询业务列表
     *
     * @param genTablePage 分页信息
     * @param genTable     业务信息
     * @return 业务集合
     */
    @Override
    public Page<GenTable> selectGenTableListPage(Page<GenTable> genTablePage, GenTable genTable) {
        QueryWrapper<GenTable> queryWrapper = Wrappers.<GenTable>query().
                like(StringUtils.isNotEmpty(genTable.getTableName()), GenTableMetadata.TABLE_NAME.getColName(), genTable.getTableName())
                .like(StringUtils.isNotEmpty(genTable.getTableComment()), GenTableMetadata.TABLE_COMMENT.getColName(), genTable.getTableComment());
        return genTableMapper.selectPage(genTablePage, queryWrapper);
    }

    /**
     * 查询据库列表
     *
     * @param tableNames 表名称组
     * @return 数据库表集合
     */
    @Override
    public List<GenTable> selectDbTableListByNames(String[] tableNames) {
        return genTableMapper.selectDbTableListByNames(tableNames);
    }

    /**
     * 查询所有表信息
     *
     * @return 表信息集合
     */
    @Override
    public List<GenTable> selectGenTableAll() {
        return genTableMapper.selectGenTableAll();
    }

    /**
     * 修改业务
     *
     * @param genTable 业务信息
     */
    @Override
    public void updateGenTable(GenTable genTable) {
        String options = JSONUtil.toJsonStr(genTable.getSearchParams());
        genTable.setOptions(options);
        int row = genTableMapper.updateById(genTable);
        if (row > 0) {
            List<GenTableColumn> columns = genTable.getColumns();
            if (CollectionUtil.isNotEmpty(columns)) {
                for (GenTableColumn cenTableColumn : columns) {
                    genTableColumnMapper.updateById(cenTableColumn);
                }
            }
        }
    }

    /**
     * 删除业务对象
     *
     * @param ids 需要删除的数据ID
     */
    @Override
    public void deleteGenTableByIds(String ids) {
        genTableMapper.deleteBatchIds(Arrays.stream(ids.split(",")).collect(Collectors.toList()));
        genTableColumnMapper.deleteGenTableColumnByTableIds(Convert.toLongArray(ids.split(",")));
    }

    /**
     * 导入表结构
     *
     * @param tableList 导入表列表
     */
    @Override
    public void importGenTable(List<GenTable> tableList) {
        try {
            for (GenTable table : tableList) {
                String tableName = table.getTableName();
                GenUtils.initTable(table);
                int row = genTableMapper.insert(table);
                if (row > 0) {
                    // 保存列信息
                    List<GenTableColumn> genTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName);
                    for (GenTableColumn column : genTableColumns) {
                        GenUtils.initColumnField(column, table);
                        genTableColumnMapper.insert(column);
                    }
                }
            }
        } catch (Exception e) {
            throw new HimioException("导入失败：" + e.getMessage());
        }
    }

    /**
     * 预览代码
     *
     * @param tableId 表编号
     * @return 预览数据列表
     */
    @Override
    public Map<String, String> previewCode(Long tableId) {
        // 查询表信息
        GenTable table = genTableMapper.selectGenTableById(tableId);
        // 设置主子表信息
        setSubTable(table);
        // 设置主键列信息
        setPkColumn(table);
        //设置table排序字段
        setTableSort(table);
        return TplUtils.genTpls(table);
    }

    /**
     * 生成代码（自定义路径）
     *
     * @param tableName 表名称
     */
    @Override
    public void generatorCode(String tableName) {
        // 查询表信息
        GenTable table = genTableMapper.selectGenTableByName(tableName);
        // 设置主子表信息
        setSubTable(table);
        // 设置主键列信息
        setPkColumn(table);
        //设置 options 参数
        setTableFromOptions(table);
        //设置表格排序
        setTableSort(table);
        //设置权限前缀
        setPermissionPrefix(table);
        try {
            Map<String, String> dataMap = TplUtils.genTpls(table);
            for (Map.Entry<String, String> entry : dataMap.entrySet()) {
                String path = TplUtils.getGenPathSimple(table, entry.getKey());
                log.info(entry.getKey() + " 模板生成文件路径：" + path);
                FileUtils.writeStringToFile(new File(path), entry.getValue(), StandardCharsets.UTF_8);
            }
            TplUtils.executeSql(table);
        } catch (Exception e) {
            e.printStackTrace();
            throw new HimioException("渲染模板失败，表名：" + table.getTableName());
        }
    }


    /**
     * 生成带数据权限查询的mapper
     *
     * @param genTable
     */
    @Override
    public Map<String,String> genCodeWithDataScope(GenTable table) {
        // 设置主子表信息
        setSubTable(table);
        // 设置主键列信息
        setPkColumn(table);
        Dict dict = Dict.create().set("table", table);
        return TplUtils.genMapper(dict);
    }

    /**
     * 同步数据库
     *
     * @param tableName 表名称
     */
    @Override
    public void syncDb(String tableName) {
        GenTable table = genTableMapper.selectGenTableByName(tableName);
        List<GenTableColumn> tableColumns = table.getColumns();
        List<String> tableColumnNames = tableColumns.stream().map(GenTableColumn::getColumnName).collect(Collectors.toList());

        List<GenTableColumn> dbTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName);
        if (CollectionUtil.isEmpty(dbTableColumns)) {
            throw new HimioException("同步数据失败，原表结构不存在");
        }
        List<String> dbTableColumnNames = dbTableColumns.stream().map(GenTableColumn::getColumnName).collect(Collectors.toList());

        //插入表新增的字段
        dbTableColumns.forEach(column -> {
            if (!tableColumnNames.contains(column.getColumnName())) {
                GenUtils.initColumnField(column, table);
                genTableColumnMapper.insert(column);
            }
        });

        //删除表移除的字段
        List<GenTableColumn> delColumns = tableColumns.stream().filter(column -> !dbTableColumnNames.contains(column.getColumnName())).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(delColumns)) {
            genTableColumnMapper.deleteBatchIds(delColumns.stream().map(GenTableColumn::getColumnId).collect(Collectors.toList()));
        }
    }

    /**
     * 修改保存参数校验
     *
     * @param genTable 业务信息
     */
    @Override
    public void validateEdit(GenTable genTable) {
        if (GenConstants.TPL_TREE.equals(genTable.getTplCategory())) {
            String options = JSONUtil.toJsonStr(genTable.getSearchParams());
            JSONObject paramsObj = JSONUtil.parseObj(options);
            if (StringUtils.isEmpty(paramsObj.getStr(GenConstants.TREE_CODE))) {
                throw new HimioException("树编码字段不能为空");
            } else if (StringUtils.isEmpty(paramsObj.getStr(GenConstants.TREE_PARENT_CODE))) {
                throw new HimioException("树父编码字段不能为空");
            } else if (StringUtils.isEmpty(paramsObj.getStr(GenConstants.TREE_NAME))) {
                throw new HimioException("树名称字段不能为空");
            }
        } else if (GenConstants.TPL_SUB.equals(genTable.getTplCategory())) {
            if (StringUtils.isEmpty(genTable.getSubTableName())) {
                throw new HimioException("关联子表的表名不能为空");
            } else if (StringUtils.isEmpty(genTable.getSubTableFkName())) {
                throw new HimioException("子表关联的外键名不能为空");
            }
        }
    }

    /**
     * 设置主键列信息
     *
     * @param table 业务表信息
     */
    public void setPkColumn(GenTable table) {
        for (GenTableColumn column : table.getColumns()) {
            if (column.isPk()) {
                table.setPkColumn(column);
                break;
            }
        }
        if (ObjectUtil.isNull(table.getPkColumn())) {
            table.setPkColumn(table.getColumns().get(0));
        }
        if (GenConstants.TPL_SUB.equals(table.getTplCategory())) {
            for (GenTableColumn column : table.getSubTable().getColumns()) {
                if (column.isPk()) {
                    table.getSubTable().setPkColumn(column);
                    break;
                }
            }
            if (ObjectUtil.isNull(table.getSubTable().getPkColumn())) {
                table.getSubTable().setPkColumn(table.getSubTable().getColumns().get(0));
            }
        }
    }

    /**
     * 设置主子表信息
     *
     * @param table 业务表信息
     */
    public void setSubTable(GenTable table) {
        String subTableName = table.getSubTableName();
        if (StringUtils.isNotEmpty(subTableName)) {
            table.setSubTable(genTableMapper.selectGenTableByName(subTableName));
        }
    }

    /**
     * 设置代码生成其他选项值
     *
     * @param genTable 设置后的生成对象
     */
    public void setTableFromOptions(GenTable genTable) {
        JSONObject paramsObj = JSONUtil.parseObj(genTable.getOptions());
        if (ObjectUtil.isNotNull(paramsObj)) {
            String treeCode = paramsObj.getStr(GenConstants.TREE_CODE);
            String treeParentCode = paramsObj.getStr(GenConstants.TREE_PARENT_CODE);
            String treeName = paramsObj.getStr(GenConstants.TREE_NAME);
            String parentMenuId = paramsObj.getStr(GenConstants.PARENT_MENU_ID);
            String parentMenuName = paramsObj.getStr(GenConstants.PARENT_MENU_NAME);
            String fieldName = paramsObj.getStr(GenConstants.TABLE_ORDER_FIELD_NAME);
            String sortType = paramsObj.getStr(GenConstants.TABLE_ORDER_SORT_TYPE);

            genTable.setTreeCode(treeCode);
            genTable.setTreeParentCode(treeParentCode);
            genTable.setTreeName(treeName);
            genTable.setParentMenuId(parentMenuId);
            genTable.setParentMenuName(parentMenuName);
            genTable.setParentMenuName(parentMenuName);
            genTable.setParentMenuName(parentMenuName);
            genTable.setFieldName(fieldName);
            genTable.setSortType(sortType);
        }
    }

    /**
     * 设置table排序
     *
     * @param genTable
     */
    public void setTableSort(GenTable genTable) {
        String options = genTable.getOptions();
        if (StringUtils.isNotEmpty(options)) {
            JSONObject jsonObject = JSONUtil.parseObj(options);
            if (!jsonObject.isEmpty()) {
                String fieldName = jsonObject.getStr(GenConstants.TABLE_ORDER_FIELD_NAME);
                genTable.setFieldName(fieldName);
                String sortType = jsonObject.getStr(GenConstants.TABLE_ORDER_SORT_TYPE);
                genTable.setSortType(sortType);
            }
        }
    }

    /**
     * 设置权限前缀
     *
     * @param genTable
     */
    public void setPermissionPrefix(GenTable genTable) {
        String permissionPrefix = TplUtils.getPermissionPrefix(genTable.getModuleName(), genTable.getBusinessName());
        genTable.setPermissionPrefix(permissionPrefix);
    }
}